package com.hushao.aimi.config.security;

import com.alibaba.fastjson.JSON;
import com.hushao.aimi.common.ResponseCode;
import com.hushao.aimi.common.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description: 登录失败处理类
 * @author: 胡少
 * @create: 2018-06-04 02:04
 **/
@Component
@Slf4j
public class AuthFailHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        ServerResponse sr=null;
        if (exception instanceof UsernameNotFoundException || exception instanceof BadCredentialsException) {
            sr=ServerResponse.Error(ResponseCode.USER_ACCOUNT_ERROR.getCode(),ResponseCode.USER_ACCOUNT_ERROR.getDesc());

        } else if (exception instanceof DisabledException) {
            sr=ServerResponse.Error(ResponseCode.USER_ACCOUNT_FORBIDDEN.getCode(),ResponseCode.USER_ACCOUNT_FORBIDDEN.getDesc());
        } else {
            sr=ServerResponse.Error(ResponseCode.USER_UNKNOWN_ERROR.getCode(),ResponseCode.USER_UNKNOWN_ERROR.getDesc());
        }

        String msg=JSON.toJSONString(sr);
        ServerResponse.out(response,msg);
    }

}
